Kotlin

Object Expressions and Declarations

Swift

Object expressions

                  window.addMouseListener(object : MouseAdapter() {
    override fun mouseClicked(e: MouseEvent) { /*...*/ }
​
    override fun mouseEntered(e: MouseEvent) { /*...*/ }
})
                
                  open class A(x: Int) {
    public open val y: Int = x
}
​
interface B { /*...*/ }
​
val ab: A = object : A(1), B {
    override val y = 15
}
                
👏
                  fun foo() {
    val adHoc = object {
        var x: Int = 0
        var y: Int = 0
    }
    print(adHoc.x + adHoc.y)
}
                
                  class C {
    // Private function, so the return type is the anonymous object type
    private fun foo() = object {
        val x: String = "x"
    }
​
    // Public function, so the return type is Any
    fun publicFoo() = object {
        val x: String = "x"
    }
​
    fun bar() {
        val x1 = foo().x        // Works
        val x2 = publicFoo().x  // ERROR: Unresolved reference 'x'
    }
}
                
                  fun countClicks(window: JComponent) {
    var clickCount = 0
    var enterCount = 0
​
    window.addMouseListener(object : MouseAdapter() {
        override fun mouseClicked(e: MouseEvent) {
            clickCount++
        }
​
        override fun mouseEntered(e: MouseEvent) {
            enterCount++
        }
    })
    // ...
}
                

Object declarations

                  object DataProviderManager {
    fun registerDataProvider(provider: DataProvider) {
        // ...
    }
​
    val allDataProviders: Collection<DataProvider>
        get() = // ...
}
                
                  DataProviderManager.registerDataProvider(...)
                
                  object DefaultListener : MouseAdapter() {
    override fun mouseClicked(e: MouseEvent) { ... }
​
    override fun mouseEntered(e: MouseEvent) { ... }
}
                

Companion Objects

                  class MyClass {
    companion object Factory {
        fun create(): MyClass = MyClass()
    }
}
                
                  val instance = MyClass.create()
                
                  class MyClass {
    companion object { }
}
​
val x = MyClass.Companion
                
                  class MyClass1 {
    companion object Named { }
}
​
val x = MyClass1
​
class MyClass2 {
    companion object { }
}
​
val y = MyClass2
                
                  interface Factory<T> {
    fun create(): T
}
​
class MyClass {
    companion object : Factory<MyClass> {
        override fun create(): MyClass = MyClass()
    }
}
​
val f: Factory<MyClass> = MyClass